package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.ProjectDB;
import worklog.dto.ResponseDTO;

/**
 * Handles get-project requests
 */

@WebServlet("/project")
public class Project extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProjectDB projectDB;
	private int userId;
	private ResponseDTO responder = new ResponseDTO();

    public Project() throws Exception{ super(); }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		//doGet(request, response); 
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		projectDB = new ProjectDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
    	if (projectDB.isReady()) out.print(processRequest(request));
    	else out.print(responder.showError("DB connection error"));
    	projectDB.close();
    	out.close();
	}
	
	private String processRequest(HttpServletRequest request){
    	String projects = "";
		HttpSession session = request.getSession();
		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		userId = (Integer) session.getAttribute("userId");
    	try {
    		projects = projectDB.getProject(userId).toString();
		} 
    	catch (SQLException e) {}
    	
    	return projects;
	}
}